package com.zhuzl.orderservice.service;

import com.zhuzl.orderservice.api.order.OrderApi;
import com.zhuzl.orderservice.api.stock.StockApi;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author JZY001
 */
@Service
public class BusinessService {

    private final OrderApi orderApi;
    private final StockApi stockApi;

    @Autowired
    public BusinessService(OrderApi orderApi, StockApi stockApi) {
        this.orderApi = orderApi;
        this.stockApi = stockApi;
    }

    @GlobalTransactional(rollbackFor = Exception.class)
    public void createOrder(Integer id, Integer count, Boolean orderErr, Boolean hasError) {
        // 扣减库存
        stockApi.decrease(id, count);
        // 创建订单
        orderApi.createOrder(id, count, orderErr);

        // 是否手动产生异常
        if (hasError) {
            throw new RuntimeException("系统手动产生异常");
        }
    }
}
